package com.Policing.Fragment;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.Policing.Abnormal.Abnormal_Adap;
import com.Policing.Abnormal.Abnormal_Bean;
import com.Policing.Abnormal.Abnormal_Files;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.JavaBean.AbnormalImage;
import com.Policing.JavaBean.OffSaveAbnormal;
import com.Policing.LogUtils;
import com.Policing.Okhttps.MyOkHttp;
import com.Policing.R;
import com.Policing.Repairs.CmlRequestBody;
import com.Policing.Since_case.Since_case;
import com.Policing.menu.AbnormalActivity;
import com.Policing.menu.SlideSideMenuExampleActivity;
import com.Policing.util.NetworkReceiver;
import com.demo.WaveSwipeRefreshLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lemonade.widgets.slidesidemenu.SlideSideMenuTransitionLayout;

import org.json.JSONException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/12/25.
 */

public class Abnormal extends Fragment {
    private ImageView imageView, net;
    private ListView listVie;
    private TextView title_text;
    private AbnormalActivity mainActivity;
    public Context context;
    private WaveSwipeRefreshLayout mWaveSwipeRefreshLayout;
    private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    private String url = "http://" + Ip_Set.IP + "/api/unsolvedExceptionQuery";//异常列表
    private MyOkHttp okHttp;
    private String urlOffAbnormalImage = "http://" + Ip_Set.IP + "/api/exceptionImageQuery";//获取异常的图片
    private String urlUp = "http://" + Ip_Set.IP + "/api/solveUpload";
    private RadioGroup group;
    private RadioButton btn;
    private List<String> exceptionIdList;//保存ID为了获取对应的图片数据的position
    private List<AbnormalImage> abnormalImageList;//异常图片数据
    private Button uploading;//提交离线数据
    private NetworkReceiver mNetReceiver;
    private boolean isNet = false;
    private Handler handler = new Handler();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.abnormal, null);
        Since_case.set().setOnAbnormal(true);
        return view;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        context = getActivity();
        okHttp = new MyOkHttp(getContext());
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mainActivity = (AbnormalActivity) getActivity();
        load();
        Log.i("ipipip", Ip_Set.IP);
        init();
        initNetworkReceiver();
    }

    //开启网络监听广播
    private void initNetworkReceiver() {
        mNetReceiver = new NetworkReceiver(result -> {
            isNet = result;
            if (isNet) {
                group.setVisibility(View.VISIBLE);
                net.setVisibility(View.GONE);
            } else {
                group.setVisibility(View.GONE);
                net.setVisibility(View.VISIBLE);
            }
        });
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        getActivity().registerReceiver(mNetReceiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mNetReceiver);
    }

    private void load() {
        showDialog("正在加载");
        exceptionIdList = new ArrayList<>();
        abnormalImageList = new ArrayList<>();
        Since_case.set().setOffSaveAbnormalRepair(null);
        Map<String, String> map = new HashMap<>();
        map.put("source", Since_case.set().getSource());
        okHttp.post(url, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                mainActivity.runOnUiThread(() -> dialog.cancel());
            }

            @Override
            public void requestSuccess(Response response) throws IOException, JSONException {
                String responseData = response.body().string();
                //Log.e("异常数据", responseData);
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<Abnormal_Bean>() {
                }.getType();
                final Abnormal_Bean jsonBean = gson.fromJson(responseData, type);
                mainActivity.runOnUiThread(() -> {
                    if (jsonBean.getState().equals("1")) {
                        list.clear();
                        mWaveSwipeRefreshLayout.setRefreshing(false);//停止加载动画
                        List<Abnormal_Bean.DataBean> beans = jsonBean.getData();
                        for (int i = 0; i < beans.size(); i++) {
                            Map<String, Object> map1 = new HashMap<String, Object>();
                            map1.put("pointName", beans.get(i).getPointName());
                            map1.put("pointContent", beans.get(i).getPointContent());
                            map1.put("text", beans.get(i).getText());
                            String exceptionId = beans.get(i).getExceptionId();
                            map1.put("exceptionId", exceptionId);
                            map1.put("taskPointContentId", beans.get(i).getTaskPointContentId());
                            list.add(map1);
                        }
                        mainActivity.runOnUiThread(() -> dialog.cancel());
                        if (!Since_case.set().getOnAbnormal()) //离线
                        {
                            try {
                                if (beans.size() > 0) {
                                    showDialog(getContext(), 0, beans.size(), "正在离线异常图片中");
                                    getAbnormalFile(beans, 0, beans.size());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        Abnormal_Adap abnormal_adap = new Abnormal_Adap(mainActivity, list);
                        listVie.setAdapter(abnormal_adap);
                    }
                });
            }
        });

    }


    private void init() {
        title_text = (TextView) mainActivity.findViewById(R.id.title_text);
        title_text.setText("异常处理");
        listVie = (ListView) mainActivity.findViewById(R.id.checklist);
        listVie.setOnItemClickListener((parent, view, position, id) -> {
            if (Since_case.set().getOnAbnormal()) {
                if (!isNet) {
                    showToast("请在联网情况下切换离线模式使用");
                    return;
                }
            }
            Intent intent = new Intent(mainActivity, Abnormal_Files.class);
            intent.putExtra("exceptionId", String.valueOf(list.get(position).get("exceptionId")));
            intent.putExtra("taskPointContentId", String.valueOf(list.get(position).get("taskPointContentId")));
            startActivity(intent);
        });
        imageView = (ImageView) mainActivity.findViewById(R.id.opmenu);
        imageView.setOnClickListener(v -> {
            mainActivity.finish();
            /*SlideSideMenuTransitionLayout mSlideSideMenu= (SlideSideMenuTransitionLayout)getActivity().findViewById(R.id.slide_side_menu);
            mSlideSideMenu.toggle();*/
        });

        mWaveSwipeRefreshLayout = (WaveSwipeRefreshLayout) getActivity().findViewById(R.id.main_swipe);
        mWaveSwipeRefreshLayout.setColorSchemeColors(Color.WHITE, Color.WHITE);//设置水滴中旋转动画的颜色，参数1:水滴落下过程中的颜色，参数2:水滴已经落下后的颜色
        mWaveSwipeRefreshLayout.setWaveColor(0xFF3794fc);//设置水滴样色
        mWaveSwipeRefreshLayout.setMaxDropHeight(1500);//设置最大下拉高度
        mWaveSwipeRefreshLayout.setOnRefreshListener(() -> {
            //模拟3秒的加载过程
            if (isNet) {
                //接下来可以刷新ListView
                handler.postDelayed(this::load, 1200);
            } else {
                mWaveSwipeRefreshLayout.setRefreshing(false);//停止加载动画
                showToast("网络连接异常");
            }

        });
        group = (RadioGroup) mainActivity.findViewById(R.id.group);
        net = (ImageView) mainActivity.findViewById(R.id.iv_net);
        net.setOnClickListener(v -> showToast("无网络状态"));
        uploading = (Button) mainActivity.findViewById(R.id.uploading);
        uploading.setOnClickListener(v -> {
            //在这里提交视频
            if (Since_case.set().getOffSaveAbnormalRepair() != null) {
                int size1 = Since_case.set().getOffSaveAbnormalRepair().size();
                if (size1 > 0) {
                    showDialog(getContext(), 0, size1, "正在上传异常处理");
                    for (int i = 0; i < size1; i++) {
                        submitOffAbnormal(i);
                    }
                } else {
                    showToast("请添加异常处理后再提交");
                }
            } else {
                showToast("请添加异常处理后再提交");
            }
        });
        group.setVisibility(View.VISIBLE);
        btn = (RadioButton) mainActivity.findViewById(R.id.btn_week);
        group.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.btn_week:
                    Since_case.set().setOnAbnormal(true);
                    uploading.setVisibility(View.GONE);
                    load();
                    break;
                case R.id.btn_day:
                    Since_case.set().setOnAbnormal(false);
                    btn.setBackground(getResources().getDrawable(R.drawable.tv_btn_bg));
                    uploading.setVisibility(View.VISIBLE);
                    load();
                    break;
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    //离线图片
    private void getAbnormalFile(final List<Abnormal_Bean.DataBean> beans, final int i, final int size) {
        final String exceptionId = beans.get(i).getExceptionId();
        Map<String, String> map = new HashMap<>();
        map.put("exceptionId", exceptionId);
        map.put("source", Since_case.set().getSource());
        Log.e("数据", "getAbnormalFile: " + i + "size" + size);
        okHttp.post(urlOffAbnormalImage, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                showToast("离线图片失败");
                Log.e("离线数据", "requestFail: ");
            }

            @Override
            public void requestSuccess(Response response) throws IOException, JSONException {
                String responseData = response.body().string();
                Log.e("数据", "requestSuccess: " + i + responseData);
                Gson gson = new Gson();
                AbnormalImage image = gson.fromJson(responseData, AbnormalImage.class);
                if (image.getState().equals("1")) {
                    progressDialog.setProgress(i + 1);
                    exceptionIdList.add(exceptionId);
                    abnormalImageList.add(image);
                    if (i == size - 1) {
                        cancelDialog(result -> {
                            Since_case.set().setExceptionIdList(exceptionIdList);
                            Since_case.set().setAbnormalImageList(abnormalImageList);
                            showDialog(getContext(), 0, exceptionIdList.size(), "正常离线异常音频");
                            offVoice(exceptionIdList, 0, exceptionIdList.size());
                        });
                    } else {
                        int position = i;
                        position++;
                        getAbnormalFile(beans, position, beans.size());
                    }
                }
            }
        });
    }

    //离线视频
    private void offVideoData(final List<String> exceptionId, final int j, final int size) {
        progressDialog.setProgress(j + 1);
        final String path = "http://" + Ip_Set.IP + "/api/exceptionVideoDownload?exceptionId=" + exceptionId.get(j) + "&source=" + Since_case.set().getSource();
        final String fileName;
        try {
            // 创建文件夹，在存储卡下
            String dirName = Environment.getExternalStorageDirectory() + "/" + "ISOS";
            File file = new File(dirName);
            // 文件夹不存在时创建
            if (!file.exists()) {
                file.mkdir();
            }
            // 下载后的文件名
            int i = path.lastIndexOf("/"); // 取的最后一个斜杠后的字符串为名
            fileName = dirName + path.substring(i, path.length());
            Log.e("123123-1", fileName);
            Log.e("123123-2", path);
            File file1 = new File(fileName);
            if (file1.exists()) {
                // 如果已经存在, 就不下载了
                if (j == size - 1) {
                    cancelDialog(result -> {

                    });
                } else {
                    handler.postDelayed(() -> {
                        offVideoData(exceptionIdList, j + 1, size);
                    }, 100);
                }
            } else {
                new Thread(() -> DOWNLOAD1(exceptionId, path, fileName, "1", j, size)).start();
            }
        } catch (NullPointerException E) {
            Log.i("2131213123123", "!2312312");
        }
    }

    //离线音频
    private void offVoice(List<String> exceptionId, final int j, final int size) {
        final String path2 = "http://" + Ip_Set.IP + "/api/exceptionVoiceDownload?exceptionId=" + exceptionId.get(j) + "&source=" + Since_case.set().getSource();
        // 创建文件夹，在存储卡下
        String dirName = Environment.getExternalStorageDirectory() + "/" + getActivity().getPackageName();
        File file = new File(dirName);
        // 文件夹不存在时创建
        if (!file.exists()) {
            file.mkdir();
        }
        // 下载后的文件名
        int i = path2.lastIndexOf("/"); // 取的最后一个斜杠后的字符串为名
        final String fileName2 = dirName + path2.substring(i, path2.length());
        File soundFile = new File(fileName2);
        Log.e("123123-3", String.valueOf(soundFile));
        Log.e("123123-5", path2);
        Log.e("123123-6", fileName2);

        new Thread(new Runnable() {
            @Override
            public void run() {
                DOWNLOAD(exceptionIdList, path2, fileName2, "2", j, size);
            }
        }).start();

    }

    private void DOWNLOAD(List<String> exceptionIdList, String path, final String fileName, String sta, final int j, final int size) {

        try {
            URL url = new URL(path);
            // 打开连接
            URLConnection conn = url.openConnection();
            // 打开输入流
            InputStream is = conn.getInputStream();
            // 创建字节流
            byte[] bs = new byte[1024];
            int len;
            OutputStream os = new FileOutputStream(fileName);
            // 写数据
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            // 完成后关闭流
            Log.e("离线音频数据", j + "download-finish" + size);
            os.close();
            is.close();
            progressDialog.setProgress(j + 1);
            if (j == size - 1) {
                cancelDialog(result -> {
                    showDialog(getContext(), 0, size, "正在离线异常视频");
                    offVideoData(exceptionIdList, 0, size);
                });
            } else {
                offVoice(exceptionIdList, j + 1, size);
            }

        } catch (Exception e) {
            e.printStackTrace();
            Log.e("离线音频数据", "e.getMessage() --- " + e.getMessage());
        }
    }

    private void DOWNLOAD1(List<String> exceptionIdList, String path, final String fileName, String sta, final int j, final int size) {
        try {
            Log.e("离线视频数据", "测试");
            URL url = new URL(path);
            // 打开连接
            URLConnection conn = url.openConnection();
            // 打开输入流
            InputStream is = conn.getInputStream();
            // 创建字节流
            byte[] bs = new byte[1024];
            int len;
            OutputStream os = new FileOutputStream(fileName);
            // 写数据
            while ((len = is.read(bs)) != -1) {
                Log.e("离线视频数据", len + "");
                os.write(bs, 0, len);
            }
            // 完成后关闭流
            Log.e("离线视频数据", "download-finish");
            os.close();
            is.close();
            if (j == size - 1) {
                cancelDialog(result -> {
                });
            } else {
                int position = j;
                position++;
                offVideoData(exceptionIdList, position, size);
            }

        } catch (Exception e) {
            e.printStackTrace();
            progressDialog.dismiss();
            isShow = true;
            showToast("视频加载出错");
            Log.e("离线视频数据", "e.getMessage()   " + e.getMessage());
        }
    }

    private ArrayList<String> mPicList; //上传的图片凭证的数据源
    private File mediaFile;//视频路径
    private File soundFile;//音频路径
    private String taskPointContentId;//路点内容id
    private String remark;//异常描述
    private String exceptionId;//异常id

    private void submitOffAbnormal(final int j) {
        OffSaveAbnormal offSaveAbnormal = Since_case.set().getOffSaveAbnormalRepair().get(j);
        mPicList = offSaveAbnormal.getmPicList();
        ;
        mediaFile = offSaveAbnormal.getMediaFile();
        soundFile = offSaveAbnormal.getSoundFile();
        taskPointContentId = offSaveAbnormal.getTaskPointContentId();
        remark = offSaveAbnormal.getRemark();
        exceptionId = offSaveAbnormal.getExceptionId();
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        int i = 0;
        for (String path : mPicList) {
            builder.addFormDataPart(taskPointContentId + "-" + i + "upload", taskPointContentId + "-" + i + ".png", RequestBody.create(MediaType.parse(i + "/png"), new File(path)));
            i++;
        }
        if (mediaFile != null) {
            builder.addFormDataPart(taskPointContentId + "mp4", taskPointContentId + "4" + ".mp4",
                    RequestBody.create(MediaType.parse("ing/mp4"), mediaFile));
        }
        if (soundFile != null) {
            builder.addFormDataPart(taskPointContentId + "mp3", taskPointContentId + "3" + ".mp3",
                    RequestBody.create(MediaType.parse("record/mp3"), soundFile));
        }
        builder.addFormDataPart("taskPointContentId", taskPointContentId)
                .addFormDataPart("exceptionId", exceptionId)
                .addFormDataPart("text", remark)
                .addFormDataPart("source", Since_case.set().getSource());
        Request.Builder request = new Request.Builder().url(urlUp)
                .post(new CmlRequestBody(builder.build()) {
                    @Override
                    public void loading(long current, long total, boolean done) {
                        Log.i("", "current:" + current + ";total:" + total);
                    }
                });
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .connectTimeout(1000, TimeUnit.SECONDS)//单位是秒
                .readTimeout(1000, TimeUnit.SECONDS)
                .build();
        okHttpClient.newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("数据", "上传失败 ");
                showToast("上传失败，请检查网络后重试");
                progressDialog.dismiss();
            }

            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful() || response == null || response.body() == null) {
                    //返回值处理
                    showToast("上传失败，请检查网络后重试");
                    progressDialog.dismiss();
                    Log.e("数据", "失败 ");
                } else {
                    progressDialog.setProgress(j + 1);
                    if (mediaFile != null) {
                        if (mediaFile.exists()) {
                            mediaFile.delete();
                        }
                    }
                    if (soundFile != null) {
                        if (soundFile.exists()) {
                            soundFile.delete();
                        }
                    }
                    if (j == Since_case.set().getOffSaveAbnormalRepair().size() - 1) {//所有的异常视频上传成功
                        Log.e("数据", "上传成功 ");
                        progressDialog.dismiss();
                        List<OffSaveAbnormal> list = new ArrayList<>();
                        Since_case.set().setOffSaveAbnormalRepair(list);//清空数据
                        load();//刷新加载
                    }
                }
            }
        });
    }


    private void showToast(final String msg) {
        mainActivity.runOnUiThread(() -> Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show());
    }

    private ProgressDialog progressDialog, dialog;
    private Boolean isShow = true;

    private void showDialog(String msg) {
        LogUtils.d("测试打开弹窗");
        mainActivity.runOnUiThread(() -> {
            dialog = new ProgressDialog(getContext());
            dialog.setTitle(msg);
            dialog.setMessage("Loading...");
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        });
    }

    private void showDialog(final Context context, int i, final int size, final String msg) {
        try {
            if (isShow) {
                isShow = false;
                getActivity().runOnUiThread(() -> {
                    progressDialog = new ProgressDialog(context);
                    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                    progressDialog.setTitle(msg);
                    progressDialog.setMessage("Loading...");
                    progressDialog.setMax(size);
                    progressDialog.setCanceledOnTouchOutside(false);
                    progressDialog.show();
                    //关闭进度圈圈
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void cancelDialog(NetworkReceiver.request request) {
        getActivity().runOnUiThread(() -> {
            progressDialog.dismiss();
            isShow = true;
            request.requestResult(true);
        });
    }
}
